package com.example.lists;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author hej
 * @date 2022/11/4 10:45
 */
public class ListNest {
    public static void main(String[] args) {
        List<User> list = new ArrayList<>();
        List<User> list2 = new ArrayList<>();
        User user ;
        for(int i=0; i<1000000; i++){
            user = new User();
            user.setId(i);
            list.add(user);
            list2.add(user);
        }
        long start = System.currentTimeMillis();
        //List<User> result = nest1(list, list2);
        List<User> result = nest2(list, list2);
        System.out.println("for循环耗时："+(System.currentTimeMillis()-start));
    }

    /**
     * 数据量大时效率极低
     * @param list1
     * @param list2
     * @return
     */
    public static List<User> nest(List<User> list1, List<User> list2){
        List<User> result = new ArrayList<>();
        for(User user : list1){
            for(User user2 : list2){
                if(user2.getId().equals(user.getId())) {
                    user.setLable(user.getId() + " --- " + user2.getId());
                    result.add(user2);
                }
            }
        }
        return result;
    }

    /**
     * 数据量大时效率更高
     * @param list1
     * @param list2
     * @return
     */
    public static List<User> nest2(List<User> list1, List<User> list2){
        Map<Integer, User> map = list2.stream().collect(Collectors.toMap(User::getId, Function.identity()));
        List<User> result = new ArrayList<>();
        for(User user : list1){
            if(map.containsKey(user.getId())) {
                user.setLable(user.getId() + " --- " + map.get(user.getId()));
                result.add(user);
            }
        }
        return result;
    }
}
